package com.example.qxfw.yjqx.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.qx.MsgMediumSmallScale;
import com.example.qxfw.common.entity.qx.TownshipForecast;
import com.example.qxfw.common.entity.qx.TownshipStation;
import com.example.qxfw.common.entity.qx.Weather;
import com.example.qxfw.common.entity.yj.Emergency;
import com.example.qxfw.common.entity.yj.EmergencyPoint;
import com.example.qxfw.common.entity.zy.BaseProduct;
import com.example.qxfw.rcyw.pojo.JobMake;
import com.example.qxfw.rcyw.service.JobMakeService;
import com.example.qxfw.ybzz.service.*;
import com.example.qxfw.yjqx.dto.*;
import com.example.qxfw.yjqx.service.EmergencyService;
import com.example.qxfw.yjqx.service.YjfwService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "应急气象-应急服务")
@RestController
@CrossOrigin
@RequestMapping("/yjfw")
public class YjfwController {

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private TownshipForecastService townshipForecastService;

    @Autowired
    private TownshipStationService townshipStationService;

    @Autowired
    private EmergencyService emergencyService;

    @Autowired
    private BaseProductService baseProductService;

    @Autowired
    private JobMakeService jobMakeService;

    @Autowired
    private MsgMediumSmallScaleService msgMediumSmallScaleService;

    @Autowired
    private YjfwService yjfwService;

    @ApiOperation("模糊查询乡镇")
    @GetMapping("/getCountry")
    public SysResult getCountry(String name) throws UnsupportedEncodingException {
        List<LayerCountryDto> layerCountryDtos = yjfwService.getCountryName(name);
        return SysResult.success(layerCountryDtos);
    }

    @ApiOperation("模糊查询地点")
    @GetMapping("/getAddress")
    public SysResult getAddress(String name){
        List<EmergencyPoint> emergencyPoints = yjfwService.listPointByName(name);
        return SysResult.success(emergencyPoints);
    }

    @ApiOperation("获取应急服务类型")
    @GetMapping("/getEmergencyType")
    public SysResult getEmergencyType(String paramName){
        List<String> templates = sysConfigService.getTemplates(paramName);
        return SysResult.success(templates);
    }

    @ApiOperation("获取天气信息")
    @GetMapping("/getWeather")
    public SysResult getWeather(){
        List<Weather> weathers = weatherService.getWeather();
        return SysResult.success(weathers,weathers.size());
    }

    @ApiOperation("获取风力信息")
    @GetMapping("/getWind")
    public SysResult getWind(){
        List<Weather> weathers = weatherService.getWind();
        return SysResult.success(weathers,weathers.size());
    }

    @ApiOperation("获取风向信息")
    @GetMapping("/getWindd")
    public SysResult getWindd(){
        List<Weather> weathers = weatherService.getWindd();
        return SysResult.success(weathers,weathers.size());
    }

    @ApiOperation("获取预报数据")
    @PostMapping("/getTownshipForecast")
    public SysResult getTownshipForecast(@RequestBody RegionFcstDto regionFcstDto){
        List<TownshipForecast> list = townshipForecastService.listByRegion(regionFcstDto);
        return SysResult.success(list);
    }

    @ApiOperation("查询站点信息")
    @GetMapping("/getTownshipStation")
    public SysResult getTownshipStation(String city){
        List<TownshipStation> list = townshipStationService.getList1(city);
        return SysResult.success(list);
    }

    @ApiOperation("保存应急信息")
    @PostMapping("/saveEmergency")
    public SysResult saveEmergency(@RequestBody Emergency emergency){
        Integer rows = emergencyService.save(emergency);


        return SysResult.success(rows);
    }

    @ApiOperation("获取应急编号")
    @GetMapping("/getEmergencyId")
    public SysResult getEmergencyId(){
        String maxId = emergencyService.getMaxId();
        return SysResult.success(maxId);
    }

    @ApiOperation("更新应急信息")
    @PostMapping("/updateEmergency")
    public SysResult updateEmergency(@RequestBody Emergency emergency){
        Integer rows = emergencyService.update(emergency);
        return SysResult.success(rows);
    }

    @ApiOperation("获取应急服务产品信息")
    @GetMapping("/getBaseProduct")
    public SysResult getBaseProduct(String productName,String productType){
        List<BaseProduct> list = baseProductService.getList2(productName, productType);
        return SysResult.success(list);
    }

    @ApiOperation("更新应急产品信息")
    @PostMapping("/updateBaseProduct")
    public SysResult updateBaseProduct(@RequestBody BaseProduct baseProduct){
        Integer rows = baseProductService.updateProduct(baseProduct);
        return SysResult.success(rows);
    }

    @ApiOperation("保存应急产品信息")
    @PostMapping("/saveBaseProduct")
    public SysResult saveBaseProduct(@RequestBody BaseProduct baseProduct){
        Integer rows = baseProductService.save(baseProduct);
        return SysResult.success(rows);
    }

    @ApiOperation("更新日常任务")
    @PostMapping("/updateJobMake")
    public SysResult updateJobMake(JobMake jobMake){
        Integer rows = jobMakeService.update(jobMake);
        return SysResult.success(rows);
    }

    @ApiOperation("实况分析")
    @PostMapping("/skfx")
    public SysResult skfx(@RequestBody SkfxDto skfxDto){
        Map<String,String> fieldMap = new HashMap<>();
        fieldMap.put("降水","rain");
        fieldMap.put("空气温度","drybulbtemp");
        fieldMap.put("最高气温","maxtemp");
        fieldMap.put("最低气温","mintemp");
        fieldMap.put("10分钟风向","windd10ms");
        fieldMap.put("最大风向","maxwindd");
        fieldMap.put("最大风速","maxwindv");
        fieldMap.put("本站气压","stationpress");
        fieldMap.put("阵风风向","hexmaxwindd");

        Map<String,List<MsgMediumSmallScale>> Map = new HashMap<>();
        List<MsgMediumSmallScale> msgMediumSmallScalesAll = new ArrayList<>();
        String[] name = skfxDto.getDbName().split(";");
        for (String iname:name){
            List<MsgMediumSmallScale> msgMediumSmallScales = new ArrayList<>();
            switch (iname){
                //平均
                case "空气温度":
                case "本站气压":
                    msgMediumSmallScales = msgMediumSmallScaleService.listSkAvg(fieldMap.get(iname),skfxDto.getTime1(),skfxDto.getTime2(),skfxDto.getLon(),skfxDto.getLat(),skfxDto.getRadius(),skfxDto.getPos());
                    break;
                //最高
                case "最高气温":
                case "最大风速":
                    msgMediumSmallScales = msgMediumSmallScaleService.listSkMax(fieldMap.get(iname),skfxDto.getTime1(),skfxDto.getTime2(),skfxDto.getLon(),skfxDto.getLat(),skfxDto.getRadius(),skfxDto.getPos());
                    break;
                //最低
                case "最低气温":
                    msgMediumSmallScales = msgMediumSmallScaleService.listSkMin(fieldMap.get(iname),skfxDto.getTime1(),skfxDto.getTime2(),skfxDto.getLon(),skfxDto.getLat(),skfxDto.getRadius(),skfxDto.getPos());
                    break;
                //求和
                case "降水":
                    msgMediumSmallScales = msgMediumSmallScaleService.listSkSum(fieldMap.get(iname),skfxDto.getTime1(),skfxDto.getTime2(),skfxDto.getLon(),skfxDto.getLat(),skfxDto.getRadius(),skfxDto.getPos());
                    break;
                //平均
                case "最大风向":
                case "10分钟风向":
                case "阵风风向":
                    msgMediumSmallScales = msgMediumSmallScaleService.listSkMax1(fieldMap.get(iname),skfxDto.getTime1(),skfxDto.getTime2(),skfxDto.getLon(),skfxDto.getLat(),skfxDto.getRadius(),skfxDto.getPos());
                    break;
            }

            msgMediumSmallScalesAll.addAll(msgMediumSmallScales);
        }


        Map<String, MsgMediumSmallScale> mergedMap = new HashMap<>();
        for (MsgMediumSmallScale msg : msgMediumSmallScalesAll) {
            String key = msg.getStationid();
            if (mergedMap.containsKey(key)) {
                MsgMediumSmallScale mergedMsg = mergedMap.get(key);
                mergeObjects(mergedMsg, msg);
            } else {
                mergedMap.put(key, msg);
            }
        }
        return SysResult.success(mergedMap);
    }

    private static void mergeObjects(Object target, Object source) {
        Class<?> targetClass = target.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object sourceValue = field.get(source);
                if (sourceValue != null) {
                    field.set(target, sourceValue);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    @ApiOperation("地理分析")
    @PostMapping("/dlfx")
    public SysResult dlfx(@RequestBody DlfxDto dlfxDto) throws UnsupportedEncodingException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        List<LayerRcoDto> layerRcoDtos = yjfwService.listLayerByScope(dlfxDto);
        return SysResult.success(layerRcoDtos);
    }

    @ApiOperation("地理分析")
    @PostMapping("/multiplePosDlfx")
    public SysResult MultiplePosDlfx(@RequestBody MultiplePosDlfxDto multiplePosDlfxDto) throws UnsupportedEncodingException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        List<List<List<Double>>> posList = multiplePosDlfxDto.getPosList();
        List<LayerRcoDto> layerRcoDtoList = new ArrayList<>();
        for (List<List<Double>> pos : posList) {
            DlfxDto dlfxDto = new DlfxDto();
            dlfxDto.setLayerName(multiplePosDlfxDto.getLayerName());
            dlfxDto.setPos(pos);
            List<LayerRcoDto> layerRcoDtos1 = yjfwService.listLayerByScope(dlfxDto);
            layerRcoDtoList.addAll(layerRcoDtos1);
        }

        List<LayerRcoDto> distinctLayerRcoDtoList = layerRcoDtoList.stream().distinct().collect(Collectors.toList());
        return SysResult.success(distinctLayerRcoDtoList);
    }

    @ApiOperation("地理分析")
    @PostMapping("/posListDlfx")
    public SysResult posListDlfx(@RequestBody MultiplePosDlfxDto multiplePosDlfxDto){
        List<LayerRcoDto> layerRcoDtoList = new ArrayList<>();
        try {
            layerRcoDtoList = yjfwService.listLayerByScopeList(multiplePosDlfxDto);
            List<LayerRcoDto> distinctLayerRcoDtoList = layerRcoDtoList.stream().distinct().collect(Collectors.toList());
            return SysResult.success(distinctLayerRcoDtoList);
        } catch (Exception e){
            e.printStackTrace();
            System.err.println("地理分析失败");
            return SysResult.fail("地理分析失败");
        }

    }

    @ApiOperation("生成产品")
    @PostMapping("/createProduct")
    public Object createProduct(String issueNum, String userName, String phone, String title,
                                String type, String skName, String skData, String ybData, String dlData,
                                String layerName, MultipartFile[] images,String date){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parse = sdf.parse(date);
            return yjfwService.createProduct(year, issueNum, userName, phone, title, type, skName, skData, ybData, dlData, layerName, images, parse);
        } catch (Exception e){
            e.printStackTrace();
            return "时间错误";
        }
    }

    @ApiOperation("插入实况，预报，地理表格数据")
    @PostMapping("/wordInsertData")
    public Object wordInsertData(String skName, String skData, String ybData, String dlData, String layerName, MultipartFile[] images){
        ApplicationHome applicationHome = new ApplicationHome(YjfwController.class);
        String resourcePath = "templates/yjfwTemp/应急文档模板.docx";
        String targetPath = applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\temp\\产品文档.docx";
        return yjfwService.insertData(resourcePath,targetPath,skName,skData,ybData,dlData,layerName,images);
    }

    @ApiOperation("获取模板")
    @GetMapping("/getTemplate")
    public Object getTempalate() throws IOException {
        ApplicationHome applicationHome = new ApplicationHome(YjfwController.class);
        //文档保存路径
        String filepath = applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\templates\\yjfwTemp\\应急文档模板.docx";
        InputStream inputStream = Files.newInputStream(Paths.get(filepath));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "应急模板文档.docx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(byteArray.length);
        return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
    }

}
